<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :xs="12" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="安全奖及未休奖补贴" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwAqhjwxjbtTable.loading" :columns="cwAqhjwxjbtTable.columns"
          :dataSource="cwAqhjwxjbtTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :rowSelection="true" :actionButton="true" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>
<script>
import { mapState } from 'vuex'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { getAction } from '@/api/manage'
export default {
  name: 'CwAqhjwxjbtTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
      model: { year: '' }, // 初始为空，由watch同步全局年度
      validatorRules: {
        unit: [{ required: true, message: '请选择单位!' }],
        year: [{ required: true, message: '请选择年度!' }],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwAqhjwxjbt'],
      tableKeys: ['cwAqhjwxjbt'],
      activeKey: 'cwAqhjwxjbt',
      confirmLoading: false,
      cwAqhjwxjbtTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: '姓名', key: 'name', type: FormTypes.input, width: "200px", placeholder: '请输入${title}', defaultValue: '' },
          { title: '安全奖、未休假补贴', key: 'aqWx', type: FormTypes.select, dictCode: "aq_wx", width: "200px", placeholder: '请选择${title}', defaultValue: '' },
          {
            title: '金额(元)',
            key: 'money',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [{ pattern: /^\d+(\.\d{1,2})?$/, message: "${title}格式不正确，仅支持非负整数或最多2位小数" }],
          },
          { title: '是否派遣', key: 'dispatch', type: FormTypes.select, dictCode: "dispatch", width: "200px", placeholder: '请选择${title}', defaultValue: '' },
        ]
      },
      url: {
        add: "/cw/cwAqhjwxjbtTj/add",
        edit: "/cw/cwAqhjwxjbtTj/edit",
        cwAqhjwxjbt: { list: '/cw/cwAqhjwxjbtTj/queryCwAqhjwxjbtByMainId' },
        getByYear: '/cw/cwAqhjwxjbtTj/list'
      },
      isManualChange: false // 标记是否手动修改过表单年度
    }
  },
  props: {
    disabled: { type: Boolean, default: false, required: false },
    scene: { // 接收 Modal 传递的场景值
      type: String,
      default: ''
    }
  },
  computed: {
    formDisabled() { return this.disabled },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },
  created() {
    // 初始化时同步全局年度
    this.model.year = this.globalYear
    const scene = this.scene; // 接收 Modal 传递的 scene（add/edit）
    this.currentScene = scene; // 存储到本地变量，后续复用
    console.log(scene)
    if (scene=='add'){
      this. handleYearChange(this.model.year)
    }
  },
  methods: {
    addBefore() { this.cwAqhjwxjbtTable.dataSource = [] },
    getAllTable() { return Promise.all(this.tableKeys.map(key => getRefPromise(this, key))) },
    editAfter() {
      this.$nextTick(() => { })
      if (this.model.id) {
        getAction(this.url.cwAqhjwxjbt.list, { id: this.model.id }).then(res => {
          this.cwAqhjwxjbtTable.dataSource = res.success ? res.result.records || [] : []
        }).finally(() => { this.cwAqhjwxjbtTable.loading = false })
      }
    },
    validateSubForm(allValues) {
      return new Promise((resolve) => { Promise.all([]).then(() => resolve(allValues)) })
    },
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return { ...main, cwAqhjwxjbtList: allValues.tablesValue[0].values }
    },
    validateError(msg) { this.$message.error(msg) },
    close() {
      this.visible = false
      this.$emit('close')
      this.$refs.form && this.$refs.form.clearValidate()
    },
    async handleYearChange(year) {
      if (!year) {
        this.model = { unit: this.model.unit };
        this.cwAqhjwxjbtTable.dataSource = [];
        return;
      }
      this.confirmLoading = true;
      this.cwAqhjwxjbtTable.loading = true;
      try {
        const yearResponse = await getAction(this.url.getByYear, { year })
        if (yearResponse.success && yearResponse.result.records.length > 0) {
          const mainRecord = yearResponse.result.records[0]
          this.model = { ...this.model, ...mainRecord }
          if (mainRecord.id) {
            const subResponse = await getAction(this.url.cwAqhjwxjbt.list, { id: mainRecord.id })
            this.cwAqhjwxjbtTable.dataSource = subResponse.success ? subResponse.result.records || [] : []
          } else {
            this.$message.warning('未获取到关联ID，无法加载数据')
            this.cwAqhjwxjbtTable.dataSource = []
          }
        } else {
          this.$message.warning(yearResponse.message || '该年度暂无数据')
          this.cwAqhjwxjbtTable.dataSource = []
          this.model.id = undefined
        }
      } catch (error) {
        console.error('查询接口异常：', error)
        this.$message.error('查询失败，请刷新页面重试或联系管理员')
        this.cwAqhjwxjbtTable.dataSource = []
      } finally {
        this.confirmLoading = false
        this.cwAqhjwxjbtTable.loading = false
      }
    }
  }
}
</script>
<style scoped></style>